﻿using FreeSql;
using GameServer.Database;
using GameServer.Model;
using Proto;
using Summer;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GameServer.Mgr
{
    public class CharacterManager:Singleton<CharacterManager>
    {
        private ConcurrentDictionary<int, Character> m_CharacterCache = new ConcurrentDictionary<int, Character>();
        IBaseRepository<DbCharacter> repo = Db.fsql.GetRepository<DbCharacter>();
        public CharacterManager() 
        {
            Scheduler.Instance.AddTask(Save, 5);
        }
        public Character Create(DbCharacter dbchr)
        {
            Character chr = new Character(dbchr.Id, new Vector3Int(dbchr.X, dbchr.Y, dbchr.Z), Vector3Int.zero, dbchr.Speed,dbchr)
            {
            };
            m_CharacterCache[chr.entityId]=chr;
            EntityManager.Instance.AddEntity(dbchr.SpaceId,chr);
            return chr;
        }

        public void Remove(int id)
        {
            Character chr;
            if (m_CharacterCache.TryRemove(id, out chr))
            {
                EntityManager.Instance.RemoveEntity(chr.Data.SpaceId,chr);

            }
        }

        public void Clear()
        {
            m_CharacterCache.Clear();
        }
        public Character Get(int id)
        {
            return m_CharacterCache.GetValueOrDefault(id,null);
        }
        public void Save()
        {
            foreach (var item in m_CharacterCache.Values)
            {
                repo.UpdateAsync(item.Data);
            }
        }
    }
}
